Basic Practice Problems in C

Posted on December 18, 2023 by Vishesh Namdev
Python C C++ Java
C Programming Language

Basic Practice Problems based on chapter which you learn in previous Tutorials.

1. Addition of two numbers

#include <stdio.h>Copy Code
int main() {
// Declare variables to store the numbers
int num1, num2;

// Prompt the user to enter the first number
printf("Enter the first number: ");
scanf("%d", &num1);

// Prompt the user to enter the second number
printf("Enter the second number: ");
scanf("%d", &num2);

// Calculate the sum
int sum = num1 + num2;

// Display the result
printf("Sum: %d\n", sum);

return 0;
}

2. Find the size of int, char, float and double

#include <stdio.h>Copy Code
int main() {
// Find the size of int
printf("Size of int: %lu bytes\n", sizeof(int));

// Find the size of char
printf("Size of char: %lu bytes\n", sizeof(char));

// Find the size of double
printf("Size of double: %lu bytes\n", sizeof(double));

// Find the size of float
printf("Size of float: %lu bytes\n", sizeof(float));

return 0;
}
1. sizeof(int): Returns the size of an int in bytes.
2. sizeof(char): Returns the size of a char in bytes.
3. sizeof(double): Returns the size of a double in bytes.
4. sizeof(float): Returns the size of a float in bytes.

3. Find the Quotient and Remainders of given number

#include <stdio.h>Copy Code
int main() {
// Declare variables
int dividend, divisor, quotient, remainder;

// Get input from the user
printf("Enter the dividend: ");
scanf("%d", ÷nd);

printf("Enter the divisor: ");
scanf("%d", &divisor);

// Calculate quotient and remainder
quotient = dividend / divisor;
remainder = dividend % divisor;

// Display the result
printf("Quotient: %d\n", quotient);
printf("Remainder: %d\n", remainder);

return 0;
}

1. dividend is the number to be divided.
2. divisor is the number by which the division is performed.
3. quotient is the result of the division (dividend / divisor).
4. remainder is the remainder of the division (dividend % divisor).

4. Swap two numbers

Swapping two number in C programming language means exchanging the values of two variables. Suppose you have two variable var1 & var2. Value of var1 is 20 & value of var2 is 40.

#include <stdio.h>Copy Code
int main() {
int num1, num2;

printf("Enter the first number: ");
scanf("%d", &num1);

printf("Enter the second number: ");
scanf("%d", &num2);

// Swap without using a temporary variable
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;

printf("After swapping:\n");
printf("First number: %d\n", num1);
printf("Second number: %d\n", num2);

return 0;
}